package com.newlink.building.common_base.notifications

import android.Manifest
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.graphics.Color
import android.media.RingtoneManager
import android.net.Uri
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.alibaba.android.arouter.core.LogisticsCenter
import com.alibaba.android.arouter.launcher.ARouter
import com.newlink.building.common_base.R
import com.newlink.building.common_base.constant.NL_Key
import com.newlink.building.common_base.constant.Base_RouterPath
import com.newlink.building.common_base.event.AlarmNotifyBean
import com.newlink.building.common_base.event.EmergencyMsgBean
import com.newlink.building.common_base.event.HandleEmergencyActionBean
import com.newlink.building.common_base.utils.NLog


/**
 * 通知相关
 * Created by Jake on 2022/9/16.
 */
class NotificationHandler(private val context: Context) {
    companion object {
        private const val IMPORTANCE_MSG_ID = 2003
        private const val EMERGENCY_MSG_ID = 2002
        private const val IMPORTANCE_MSG_TAG = "Emergency Msg"
    }

    private val notificationManager: NotificationManagerCompat by lazy {
        NotificationManagerCompat.from(context)
    }

    fun displayEmergencyNotification(bean: EmergencyMsgBean) {
        notificationManager.cancel(IMPORTANCE_MSG_ID)
        val channelId = context.getString(R.string.default_notification_channel_id)
        val channelName = context.getString(R.string.default_notification_channel_name)
        val defaultNotifySound: Uri =
            RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
        val postcard = ARouter.getInstance().build(Base_RouterPath.PATH_MSG)
        LogisticsCenter.completion(postcard)
        val intent = Intent(context, postcard.destination).apply {
            action = "go_msg"
            putExtra("emergencyBean", bean)
        }

        NLog.e("发送通知的title ::::  " + bean.data.title)
        val pendingIntent: PendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            PendingIntent.getActivity(
                context,
                100,
                intent,
                PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_ONE_SHOT
            )
        } else {
            PendingIntent.getActivity(
                context, 101, intent,
                PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE
            )
        }

        val notificationBuilder: NotificationCompat.Builder =
            NotificationCompat.Builder(context, channelId)

        notificationBuilder.setContentTitle(bean.data.title)
            .setContentText(bean.data.content)
            .setSmallIcon(R.mipmap.logo)
            .setLargeIcon(BitmapFactory.decodeResource(context.resources, R.mipmap.logo))
            .setAutoCancel(true).setSound(defaultNotifySound).setContentIntent(pendingIntent)

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
            val notificationChannel = NotificationChannel(
                channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT
            )
            notificationManager.createNotificationChannel(notificationChannel)
        }
        NLog.i("发送通知的id" + bean.data.id)
        notificationManager.notify(IMPORTANCE_MSG_ID, notificationBuilder.build())
    }

    fun displayEmergencyKcpNotification(bean: EmergencyMsgBean) {
        notificationManager.cancel(IMPORTANCE_MSG_ID)
        val channelId = context.getString(R.string.default_notification_channel_id)
        val channelName = context.getString(R.string.default_notification_channel_name)
        val defaultNotifySound: Uri =
            RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
        val postcard = ARouter.getInstance().build(Base_RouterPath.PATH_MSG)
        LogisticsCenter.completion(postcard)
        val intent = Intent(context, postcard.destination).apply {
            action = "go_msg"
            putExtra("emergencyBean", bean)
        }

        NLog.e("displayEmergencyKcpNotification 发送通知的title ::::  " + bean.data.title)
//        val pendingIntent: PendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            PendingIntent.getActivity(context, 100, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_ONE_SHOT)
//        } else {
//            PendingIntent.getActivity(context, 101, intent,
//                PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE)
//        }
        val pendingIntent: PendingIntent =
            PendingIntent.getActivity(
                context,
                100,
                intent,
                PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_ONE_SHOT
            )

        val notificationBuilder: NotificationCompat.Builder =
            NotificationCompat.Builder(context, channelId)

        notificationBuilder.setContentTitle(bean.data.title)
            .setContentText(bean.data.content)
            .setSmallIcon(R.mipmap.logo)
            .setPriority(NotificationCompat.PRIORITY_MAX)
//            .setLargeIcon(BitmapFactory.decodeResource(context.resources, R.mipmap.app_logo))
            .setAutoCancel(true).setSound(defaultNotifySound).setContentIntent(pendingIntent)

//        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
//            val notificationChannel = NotificationChannel(
//                channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT
//            )
//            notificationManager.createNotificationChannel(notificationChannel)
//        }
        NLog.i("发送通知的id" + bean.data.id)
        if (ActivityCompat.checkSelfPermission(
                context,
                Manifest.permission.POST_NOTIFICATIONS
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            return
        }
//        notificationManager.notify(IMPORTANCE_MSG_ID, notificationBuilder.build())
    }

    fun displayAlarmKcpNotification(bean: AlarmNotifyBean.Data) {
        notificationManager.cancel(IMPORTANCE_MSG_ID)
        val channelId = context.getString(R.string.default_notification_channel_id)
        val channelName = context.getString(R.string.default_notification_channel_name)
        val defaultNotifySound: Uri =
            RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
//        val postcard = ARouter.getInstance().build(RouterPath.PATH_MSG)

        val postcard = ARouter.getInstance().build(Base_RouterPath.PATH_HOME)
        LogisticsCenter.completion(postcard)

        val intent = Intent(context, postcard.destination).apply {
            putExtra(NL_Key.TAB_INDEX, 2)
            putExtra(NL_Key.SUB_TAB_INDEX, 2)
        }

        NLog.e("displayAlarmKcpNotification 发送通知的title ::::  " + bean.devName)
        val pendingIntent: PendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            PendingIntent.getActivity(
                context,
                100,
                intent,
                PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_ONE_SHOT
            )
        } else {
            PendingIntent.getActivity(context, 101, intent, PendingIntent.FLAG_ONE_SHOT)
        }

        val notificationBuilder: NotificationCompat.Builder =
            NotificationCompat.Builder(context, channelId)

        val desc = if (bean.alarmType == 1) {
            context.getString(R.string.alarm_type_tamper)
        } else {
            bean.alarmDesc
        }

        notificationBuilder.setContentTitle(context.getString(R.string.alarm_title))
            .setContentText("${bean.devName} : $desc")
            .setSmallIcon(R.mipmap.logo)
            .setPriority(NotificationCompat.PRIORITY_MAX)
//            .setLargeIcon(BitmapFactory.decodeResource(context.resources, R.mipmap.app_logo))
            .setAutoCancel(true).setSound(defaultNotifySound).setContentIntent(pendingIntent)

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
            val notificationChannel = NotificationChannel(
                channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT
            )
            notificationManager.createNotificationChannel(notificationChannel)
        }
        notificationManager.notify(IMPORTANCE_MSG_ID, notificationBuilder.build())
    }

    @RequiresApi(Build.VERSION_CODES.O)
    fun displayEmergencyRecordNotification(bean: HandleEmergencyActionBean) {
        notificationManager.cancel(EMERGENCY_MSG_ID)


        val channelId = context.getString(R.string.default_notification_channel_id)
        val channelName = context.getString(R.string.default_notification_channel_name)
        val defaultNotifySound: Uri =
            RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
        val postcard = ARouter.getInstance().build(Base_RouterPath.PATH_HOME)
        LogisticsCenter.completion(postcard)
        val intent = Intent(context, postcard.destination).apply {
            action = "go_record"
            putExtra("emergencyBean", bean)
        }

        NLog.e("displayEmergencyRecordNotification 发送通知的title ::::  " + bean.data.deviceName)
        val pendingIntent: PendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            PendingIntent.getActivity(
                context,
                100,
                intent,
                PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_ONE_SHOT
            );
        } else {
            PendingIntent.getActivity(
                context, 101, intent,
                PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE
            )
        }

        val notificationBuilder: NotificationCompat.Builder =
            NotificationCompat.Builder(context, channelId)

        notificationBuilder.setContentTitle(bean.data.deviceName)
            .setContentText(
                when (bean.data.emergencyType) {
                    0 -> "防爆"
                    1 -> "红外"
                    else -> "有人"
                }
            )
            .setSmallIcon(R.mipmap.logo)
            .setLargeIcon(BitmapFactory.decodeResource(context.resources, R.mipmap.logo))
            .setAutoCancel(true).setSound(defaultNotifySound).setContentIntent(pendingIntent)

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
            val notificationChannel = NotificationChannel(
                channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT
            ).apply {
                enableLights(true)
                lightColor = Color.RED
                setShowBadge(true)
            }
            notificationManager.createNotificationChannel(notificationChannel)
        }
        NLog.i("发送通知的id" + bean.data.mac)
        notificationManager.notify(EMERGENCY_MSG_ID, notificationBuilder.build())
    }

    private fun notify(notification: Notification, tag: String? = null) {
        NLog.i("[Notifications Manager] Notifying [$IMPORTANCE_MSG_ID] with tag [$tag]")
        // todo Android 12 问题先隐藏 FLAG_IMMUTABLE
        notificationManager.notify(tag, IMPORTANCE_MSG_ID, notification)
    }

    fun cancel(id: Int, tag: String? = null) {
        NLog.i("[Notifications Manager] Canceling [$id] with tag [$tag]")
        notificationManager.cancel(tag, id)
    }
}